angular.module('app', ['ionic', 'ngStorage'])
  .controller('mainCtrl', ['$scope', '$http', 'getAPIName', 'citys', 'getWeatherData',
    function ($scope, $http, getAPIName, citys, getWeatherData) {
      for (var i = 0; i < citys.list.citys.length; i++) {
        if (citys.list.citys[i].selected == true) {
          getWeatherData.getData(citys.list.citys[i].name).then(
            function (res) {
              $scope.weatherData = res;
            })
        }
      }
      $scope.$on('changeCity', function (e, city) {
        getWeatherData.getData(city).then(
          function (res) {
            $scope.weatherData = res;
          })
      })
    }
  ])
  .controller('leftSideCtrl', ['$scope', '$rootScope', '$ionicPopover', 'citys', function ($scope, $rootScope, $ionicPopover, citys) {
    $scope.citys = citys.list.citys
    $scope.chooseCity = function (city) {
      $scope.citys.map(function (item, i) {
        item.selected = false
      })
      city.selected = true
      $rootScope.$broadcast('changeCity', angular.copy(city.name))
    }

    $ionicPopover.fromTemplateUrl('views/addcity.html', {
      scope: $scope,
      animation: "slide-in-down-delete"
    }).then(function (popover) {
      $scope.addcityPopover = popover
    })

    $scope.addCity = {
      showPopover: function () {
        $scope.addcityPopover.show()
      },
      Submit: function () {
        if ($scope.addCity.cityName) {
          $scope.cityExists = false
          for (var i = 0; i < $scope.citys.length; i++) {
            if ($scope.citys[i].name == $scope.addCity.cityName || $scope.addCity.cityName == '该城市已在列表中') {
              $scope.cityExists = true
              $scope.addCity.cityName = '该城市已在列表中'
              $('input[name=cityname]').one('focus', function () {
                $scope.addCity.cityName = null
                $scope.$apply()
              })
              return
            }
          }

          if ($scope.cityExists == false) {
            var city = {
              name: $scope.addCity.cityName,
              selected: false
            }
            $scope.citys.push(city)
            $scope.addcityPopover.hide()
            $scope.addCity.cityName = null
          }
        }
      }
    }

    $scope.deleteCity = function (index) {
      if ($scope.citys[index].selected == true) {
        return
      }
      $scope.citys.splice(index, 1)
    }
  }])
  .service('citys', ['$localStorage', function ($localStorage) {
    this.list = $localStorage.$default({
      citys: [{
        name: '北京市',
        selected: true
      }, {
        name: '上海市',
        selected: false
      }, {
        name: '哈尔滨市',
        selected: false
      }, {
        name: '烟台市',
        selected: false
      }, {
        name: '杭州市',
        selected: false
      }, {
        name: '苏州市',
        selected: false
      }, {
        name: '郑州市',
        selected: false
      }, {
        name: '广州市',
        selected: false
      }]
    })
  }])
  .service('getAPIName', function () {
    return function getAPIName(pm25) {
      if (pm25 <= 50) return '优'
      if (pm25 <= 100) return '良'
      if (pm25 <= 150) return '轻微污染'
      if (pm25 <= 200) return '轻度污染'
      if (pm25 <= 300) return '中度污染'
      if (pm25 > 300) return '重度污染'
      if (pm25 > 500) return '已爆表！'
    }
  })
  .service('getWeatherData', function ($http, getAPIName) {
    return {
      getData: function (city) {
        var path = "http://api.map.baidu.com/telematics/v3/weather?location=" + city + "&output=json&ak=iw5m2G7ayDow8ofDdDGVUMB3&mcode=com.BaiduWeather&callback=JSON_CALLBACK"
        var promise = $http.jsonp(path).then(function (res) {
          var total = res.data.results[0];
          var today = total.weather_data[0];
          var day2 = total.weather_data[1];
          var day3 = total.weather_data[2];
          var day4 = total.weather_data[3];
          return {
            city: total.currentCity,
            pm25: total.pm25,
            pm25Name: getAPIName(total.pm25),
            today: {
              pic: today.dayPictureUrl.substring(today.dayPictureUrl.lastIndexOf('/')),
              tempers: today.temperature.replace('℃', ''),
              weather: today.weather,
              wind: today.wind,
              temper: today.date.substring(today.date.indexOf('：')).replace(')', ''),
            },
            nextThree: [{
              week: day2.date,
              pic: day2.dayPictureUrl.substring(day2.dayPictureUrl.lastIndexOf('/')),
              temper: day2.temperature,
              weather: day2.weather,
              wind: day2.wind
            }, {
              week: day3.date,
              pic: day3.dayPictureUrl.substring(day3.dayPictureUrl.lastIndexOf('/')),
              temper: day3.temperature,
              weather: day3.weather,
              wind: day3.wind
            }, {
              week: day4.date,
              pic: day4.dayPictureUrl.substring(day4.dayPictureUrl.lastIndexOf('/')),
              temper: day4.temperature,
              weather: day4.weather,
              wind: day4.wind
            }]
          }
        })
        return promise;
      }
    }
  })
  .run(function ($ionicPlatform) {
    $ionicPlatform.ready(function () {
      if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        cordova.plugins.Keyboard.disableScroll(true);
      }
      if (window.StatusBar) {
        StatusBar.styleDefault();
      }
    });
  })
